package org.tisn.qq.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map.Entry;

import org.tisn.qq.QQClient;
import org.tisn.qq.activity.HomeActivity;
import org.tisn.qq.activity.LoginProcessActivity;
import org.tisn.qq.agr.QQUser;
import org.tisn.qq.data.info.GroupInfo;
import org.tisn.qq.data.info.UserInfo;
import org.tisn.qq.events.IQQListener;
import org.tisn.qq.events.QQEvent;
import org.tisn.qq.packets.in.GetFriendGroupInfoReplyPacket;
import org.tisn.qq.packets.in.GetFriendListReplyPacket;
import org.tisn.qq.packets.in.RecVFCodePacket;
import org.tisn.qq.packets.in.ReceiveOnlineListPacket;
import org.tisn.qq.utils.Util;

import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

public class TQQServer extends Service implements IQQListener  {
	
	private static String TAG = "TQQ_Service";
	public QQClient client;
	
	public ArrayList <UserInfo> onlineList = new ArrayList<UserInfo>();
	public ArrayList <UserInfo> friendList = new ArrayList<UserInfo>();
	public ArrayList <GroupInfo> groupList = new ArrayList<GroupInfo>();
	
    private Handler handler = new Handler() {
    	@Override
        public void handleMessage(Message msg)
        {
    		Intent i;
        	switch (msg.what) {
        	case QQEvent.LOGIN_OK:
        		i = new Intent(TQQServer.this, LoginProcessActivity.class);
        		i.putExtra("cmd", "login.reply");
        		i.putExtra("do", "ok");
        		startActivity(i);
        		break;
        	case QQEvent.LOGIN_PASSWORD_WRONG:
        		i = new Intent(TQQServer.this, LoginProcessActivity.class);
        		i.putExtra("cmd", "login.reply");
        		i.putExtra("do", "pwdwrong");
        		startActivity(i);
        		break;
        	case QQEvent.LOGIN_NEED_VERIFY:
        		RecVFCodePacket packet = (RecVFCodePacket) msg.obj;
        		i = new Intent(TQQServer.this, LoginProcessActivity.class);
        		i.putExtra("re", packet.type);
        		if (packet.type == 0x0100 || packet.type == 0x0201) {
        			Bitmap b = packet.getBitmap();
            		i.putExtra("cmd", "login.reply");
            		i.putExtra("do", "needvfcode");
            		i.putExtra("bitmap", b);
        		}
        		startActivity(i);
        		break;
        	case QQEvent.IM_RECEIVED:
        		break;
        	case QQEvent.FRIEND_GET_LIST_OK:
        		GetFriendListReplyPacket packet1 = (GetFriendListReplyPacket) msg.obj;
        		i = new Intent(TQQServer.this, HomeActivity.class);
        		i.putExtra("cmd", "friendlist.all.ref");
        		for (Iterator<?> iter = packet1.getFriendList().entrySet().iterator(); iter.hasNext();) {
   				 Entry<Integer, Integer> entry = (Entry<Integer, Integer>) iter.next();
   				 UserInfo u = new UserInfo((Integer) entry.getKey());
   				 u.setGroupId((entry.getValue() & 0xFF) / 4);
   				 friendList.add(u);
   			 	}
        		startActivity(i);
        		break;
        	case QQEvent.FRIEND_GET_GROUP_NAMES_OK:
        		GetFriendGroupInfoReplyPacket packet2 = (GetFriendGroupInfoReplyPacket) msg.obj;
        		int cnt = 0;
        		for (Iterator<?> iter = packet2.getGroups().entrySet().iterator(); iter.hasNext();) {
      				 Entry<Integer, byte[]> entry = (Entry<Integer, byte[]>) iter.next();
      				 GroupInfo g = new GroupInfo();
      				 g.setId(cnt);
      				 byte[] name = entry.getValue();
      				 if (name != new byte[0]) {
      					 g.setName(Util.bytes2message(name));
      				 }
      				 boolean h = false;
      				 for (GroupInfo g1 : groupList) {
      					 if (g1.getId() == g.getId()) {
      						 h = true;
      					 }
      				 }
      				 if (!h) {
      					groupList.add(g);
      				 }
      				 cnt++;
      			 }
        		i = new Intent(TQQServer.this, HomeActivity.class);
        		i.putExtra("cmd", "friendlist.all.ref");
        		startActivity(i);
        		break;
        	case QQEvent.FRIEND_GET_ONLINE_OK:
        		ReceiveOnlineListPacket packet3 = (ReceiveOnlineListPacket) msg.obj;
        		onlineList.clear();
        		for (int uin : packet3.getOnlineList()) {
        			UserInfo u = new UserInfo(uin);
        			onlineList.add(u);
        		}
        		i = new Intent(TQQServer.this, HomeActivity.class);
        		i.putExtra("cmd", "friendlist.all.ref");
        		startActivity(i);
        	}
        }
    };
    
	@Override
	public IBinder onBind(Intent arg0) {
		return myBinder;
	}
	
	@Override
	public void onCreate() {
		Log.i(TAG , "onCreate");
		super.onCreate();
	}

	@Override
	public void onDestroy() {
		Log.i(TAG, "onDestroy");
		Logout();
		super.onDestroy();
	}
	
	public void Login(String num, byte[] pass) {
		Logout();
		client = new QQClient();
		client.setConnectionPoolFactory(new org.tisn.qq.net.PortGateFactory());
		client.setUser(new QQUser(num, pass));
		client.addQQListener(this);
		client.login();
	}
	
	public void Logout() {
		if (client != null) {
			client.logout();
			client.release();
			client = null;
		}
	}
	
	public void getFriendList() {
		client.getFriendList(0);
	}
	
	public void getGroupInfo() {
		client.getGroupInfo();
	}
	
	public void sendVFCode(String code) {
		client.sendVFCode(code);
	}
	
    public class MyBinder extends Binder{
        
        public TQQServer getService(){
            return TQQServer.this;
        }
    }
    
    private MyBinder myBinder = new MyBinder();

	public void qqEvent(QQEvent e) {
		Message msg = new Message();
		if (e.getSource() != null) {
			msg.obj = e.getSource();
		}
		msg.what = e.type;
		handler.sendMessage(msg);
	}
	
	@Override
	public void startActivity(Intent i) {
		i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		super.startActivity(i);
	}
}
